package com.kaili.basic.controlle;/**
 * Created by zengshuai on 18-4-26.
 */

import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.basic.pojo.dto.*;
import com.kaili.basic.pojo.entity.BaseCustomer;
import com.kaili.basic.pojo.entity.QueryCustomerVO;
import com.kaili.basic.service.BaseCustomerService;
import com.kaili.basic.service.BaseEmployeeService;
import com.kaili.basic.version.ApiVersion;
import com.kaili.common.entity.BaseEmployee;
import com.kaili.common.response.CommonStatus;
import com.kaili.common.response.RestStatus;
import com.kaili.common.util.LoginDetailUtils;
import com.kaili.common.util.PinYinUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author zengshuai
 * @Copyright: Copyright (c) 2017
 * @Company: 杭州凯立通信有限公司
 */
@ApiVersion(1)
@RequestMapping("/{api_version}")
@RestController
@Api(tags = "客户管理", description = "客户管理相关API")
public class BaseCustomerController {

    @Autowired
    BaseCustomerService customerService;
    @Autowired
    BaseEmployeeService employeeService;

    //新增或修改后的保存操作
    @PostMapping(value = "baseCustomer")
    @ApiOperation(value = "新增或修改后的保存操作",notes = "新增或修改后的保存操作")
    public RestStatus  addOrUpdateCustomer(@RequestBody BaseCustomerAddDto baseCustomerAddDto){
        BaseCustomer customer = new BaseCustomer();
        BeanUtils.copyProperties(baseCustomerAddDto, customer);
        List<BaseCustomer> customers = customerService.selectCustomer(customer);
            if(customer.getCustomerCode() == null){//说明是新增客户

                if (customers.size()==0) {
                    //设置客户编号，从数据库中查询当前最大ID

                    BaseCustomer baseCustomer = changeCustomer(customer);
                    BaseEmployee employee = employeeService.selectById(LoginDetailUtils.getCurrentEmployeeId());
                    baseCustomer.setCreateSite(employee.getSiteId().toString());//设置创建网点
                    customerService.addCustomer(customer);
                    return CommonStatus.ADD_OK;
                }else {
                    return CommonStatus.ADD_DEFEAT;
                }
            }else{//说明是修改
//                for (BaseCustomer c : customers) {
//                    if (!Objects.equals(c.getCustomerId(), customer.getCustomerId())) {
//                        return CommonStatus.ADD_DEFEAT_CUSTER;
//                    }
//                }
                customer.setModifyTime(new Date());
                customer.setModifyBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
                customer.setNamePinyin(PinYinUtil.toPinYin(customer.getName()));
                customer.setInitial(PinYinUtil.toSimplePinYin(customer.getName()));
                customer.setCompanyNamePinyin(PinYinUtil.toPinYin(customer.getCompanyName()));
                customerService.updateCustomer(customer);
                return CommonStatus.UPDATE_OK;
            }
    }

   @DeleteMapping(value = "baseCustomer")
   @ApiOperation(value = "删除客户",notes = "删除客户")
   public RestStatus deleteCustomer(@ModelAttribute BaseCustomerDeleteDto baseCustomerDeleteDto) {
       BaseCustomer customer = new BaseCustomer();
       customer.setCustomerCode(baseCustomerDeleteDto.getCustomerCode());
       customer.setModifyBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
       customer.setModifyTime(new Date());
       if(customerService.deleteCustomer(customer) == -1){

       }
       return CommonStatus.DELETE_OK;
   }

    @GetMapping(value = "baseCustomer/list")
    @ApiOperation(value = "根据联系人或客户公司模糊查询",notes = "根据联系人或客户公司模糊查询")
    public List<BaseCustomer> queryCustomer(@ModelAttribute BaseCustomerByLinkmanOrCompanyDto baseCustomerByLinkmanOrCompanyDto){
        BaseCustomer customer = new BaseCustomer();
        customer.setName(baseCustomerByLinkmanOrCompanyDto.getName());
        customer.setCompanyName(baseCustomerByLinkmanOrCompanyDto.getCompanyName());
        if(LoginDetailUtils.getSiteId()!=1)
            customer.setSite(LoginDetailUtils.getSiteId().longValue());
        return customerService.queryCustomer(customer);
    }


    ////条件查询获取客户详细信息
    @GetMapping(value = "baseCustomer/page")
    @ApiOperation(value = "条件查询客户详细信息",notes = "条件查询客户详细信息")
    public Page<QueryCustomerVO> queryCustomerDetails(@ModelAttribute BaseCustomerQueryDto baseCustomerQueryDto) {
        QueryCustomerVO queryCustomerVO = new QueryCustomerVO();
        queryCustomerVO.setSite(baseCustomerQueryDto.getSite());
        queryCustomerVO.setName(baseCustomerQueryDto.getName());
        queryCustomerVO.setCompanyName(baseCustomerQueryDto.getCompanyName());
        queryCustomerVO.setPage(baseCustomerQueryDto.getPage());
        queryCustomerVO.setPageSize(baseCustomerQueryDto.getPageSize());
        if(LoginDetailUtils.getSiteId()!=1)
            queryCustomerVO.setSite(LoginDetailUtils.getSiteId().longValue());
        return customerService.queryCustomerDetails(new Page<QueryCustomerVO>(queryCustomerVO.getPage(),queryCustomerVO.getPageSize()),queryCustomerVO);
    }

    @GetMapping(value = "baseCustomer/codeOrName")
    @ApiOperation(value = "根据编号或姓名拼音模糊查询",notes = "根据编号或姓名拼音模糊查询")
    public List<BaseCustomer> likeQueryCustomer(@ModelAttribute BaseCustomerNameDto baseCustomerNameDto){
        return customerService.queryCustomerCode(baseCustomerNameDto.getName());
    }

    @GetMapping(value = "baseCustomer/code")
    @ApiOperation(value = "获取客户编号",notes = "获取客户编号")
    public String findMaxCustomerCode(){
        String str= customerService.getMaxCustomerCode();
        if (StringUtils.isEmpty(str)) {
            str = "0000";
        }
        String result = String.valueOf(Integer.valueOf(str)+1);
        if (result.length() == 1){
            result = "000" + result;
        }else if (result.length() == 2){
            result = "00" + result;
        }else if (result.length() == 3){
            result = "0" + result;
        }
        return result;
    }

    @PostMapping(value = "baseCustomer/ewb")
    @ApiOperation(value = "保存操作",notes = "开单保存操作")
    public Integer  addCustomer(@Validated @RequestBody BaseCustomerAddEwbDto baseCustomerAddDto){
        BaseCustomer customer = new BaseCustomer();
        BeanUtils.copyProperties(baseCustomerAddDto,customer);
        List<BaseCustomer> customers = customerService.selectCustomer(customer);
        if (customers.size()==0) {
            BaseCustomer baseCustomer = changeCustomer(customer);
            BaseEmployee employee = employeeService.selectById(LoginDetailUtils.getCurrentEmployeeId());
            baseCustomer.setCreateSite(employee.getSiteId().toString());//设置创建网点
            baseCustomer.setSite(Long.valueOf(employee.getSiteId()));
            baseCustomer.setSettlement((long) 81);
            customerService.addCustomer(baseCustomer);
            return customerService.getCustomerId(customer).getCustomerId().intValue();
        }
        else {
            return customers.get(0).getCustomerId().intValue();
        }
    }

    private BaseCustomer changeCustomer(BaseCustomer customer){
        Long customerId = customerService.getMaxCustomerId();
        customerId = customerId + 1L;
        String custId = customerId.toString();
        switch (custId.length()) {
            case 1:
                custId = "000" + custId;
                break;
            case 2:
                custId = "00" + custId;
                break;
            case 3:
                custId = "0" + custId;
                break;
            case 4:
                custId = custId;
                break;
            default:  //超过四位限制
                break;
        }
        customer.setCustomerCode(custId);
        customer.setNamePinyin(PinYinUtil.toPinYin(customer.getName()));
        customer.setInitial(PinYinUtil.toSimplePinYin(customer.getName()));
        customer.setCompanyNamePinyin(PinYinUtil.toPinYin(customer.getCompanyName()));
        customer.setCreateTime(new Date());
        customer.setModifyTime(new Date());
        customer.setRegisterTime(new Date());
        customer.setCreateBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        customer.setModifyBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        customer.setRegisterBy(LoginDetailUtils.getCurrentEmployeeId().longValue());
        return customer;
    }
}
